from flask import Flask
from flask_migrate import Migrate
import config
from config import db, login_manager, Mail
from flask_wtf.csrf import CSRFProtect
from flask_caching import Cache
from twittor.route import login, index, logout, register, user, page_not_find, \
    edit_profile, article_editor, tinymce_upload_images, delete_Tweet, forget_password, user_list

mgrate = Migrate()
login_manager.login_view = 'login'
mail = Mail

def create_app():
    app = Flask(__name__, static_folder='./static')

    # app.config.from_object()方法用于从指定的Python模块或对象中加载配置。这个方法会将模块或对象的全局变量作为配置参数。
    app.config.from_object(config)

    db.init_app(app)
    mgrate.init_app(app, db)
    login_manager.init_app(app)
    CSRFProtect(app)
    Cache(app)
    mail.init_app(app)

    # 测试数据库是否连接成功
    # with app.app_context():  # 联系上下文
    #     with db.engine.connect() as conn:
    #         rs = conn.execute(text("select 1"))
    #         print(rs.fetchone())  # 如果链接成功就返回 (1,)

    app.add_url_rule('/', 'index', index)
    app.add_url_rule('/login', 'login', login, methods=["GET", "POST"])
    app.add_url_rule('/logout', 'logout', logout)
    app.add_url_rule('/register', 'register', register,methods=["GET", "POST"])
    app.add_url_rule('/user/<username>', 'user', user, methods=['GET', 'POST'])
    app.add_url_rule('/edit_profile', 'edit_profile', edit_profile, methods=['GET', 'POST'])
    app.add_url_rule('/article_editor', 'article_editor', article_editor, methods=['GET', 'POST'])
    app.add_url_rule('/tinymce_upload_images', 'tinymce_upload_images', tinymce_upload_images, methods=['GET', 'POST'])
    app.add_url_rule('/delete_Tweet', 'delete_Tweet', delete_Tweet, methods=['GET', 'POST'])
    app.add_url_rule('/forget_password', 'forget_password', forget_password, methods=['GET', 'POST'])
    app.add_url_rule('/user_list', 'user_list', user_list, methods=['GET', 'POST'])
    app.register_error_handler(404, page_not_find)

    return app


